<script lang="ts" setup>
import { Modal } from 'ant-design-vue';
import type { UnwrapRef } from 'vue';
import { cloneDeep } from 'lodash-es';
import { useNewExcelStore } from '@/store/modules/dcp/assessment_indicators/new_excel';

// 获取表头
const newExcelStore = useNewExcelStore();

const header: any[] = newExcelStore.getExcelHeader();
const title = ref<string>('');
const sheetName = ref<string>('');
const columns = ref<any[]>([]);

const data = ref<any[]>([]);

function getColumn() {
  for (let i = 0; i < header.length; i++) {
    columns.value.push({
      title: header[i].header,
      dataIndex: header[i].key,
      align: 'center',
    });
  }
  columns.value.push({
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    width: '10%',
    align: 'center',
    fixed: 'right',
  });
}

onMounted(() => {
  title.value = newExcelStore.getTitle();
  sheetName.value = newExcelStore.getSheetName();
  getColumn();
});
const headerTitle: any = ['generalFieldA', 'generalFieldB', 'generalFieldC',
  'generalFieldD', 'generalFieldE', 'generalFieldF',
  'generalFieldG', 'generalFieldH',
  'generalFieldI', 'generalFieldJ', 'generalFieldK', 'generalFieldL',
  'generalFieldM', 'generalFieldN', 'generalFieldO'];
// 保存
async function saveExcel() {
  // exportExcel();
  if (title.value === 'quarter') {
    const item: any = {
      isField: 'true',
      sheetName: sheetName.value,
      isDelete: 0,
    };
    for (let i = 0; i < header.length; i++) {
      item[headerTitle[i]] = header[i].header;
    }
    await addQuarterPublicSheetcreate(item);
    for (let i = 0; i < data.value.length; i++) {
      const dataItem: any = {
        isField: 'false',
        sheetName: sheetName.value,
        isDelete: 0,
      };
      const d = data.value[i];
      for (let j = 0; j < header.length; j++) {
        dataItem[headerTitle[j]] = d[header[j].key];
      }
      await addQuarterPublicSheetcreate(dataItem);
    }
  }
  else {
    const item: any = {
      isField: 'true',
      sheetName: sheetName.value,
      isDelete: 0,
    };
    for (let i = 0; i < header.length; i++) {
      item[headerTitle[i]] = header[i].header;
    }
    await addYunWangPublicSheetcreate(item);
    for (let i = 0; i < data.value.length; i++) {
      const dataItem: any = {
        isField: 'false',
        sheetName: sheetName.value,
        isDelete: 0,
      };
      const d = data.value[i];
      for (let j = 0; j < header.length; j++) {
        dataItem[headerTitle[j]] = d[header[j].key];
      }
      await addYunWangPublicSheetcreate(dataItem);
    }
  }
}

// 编辑和删除
const editableData: UnwrapRef<Record<string, any>> = reactive({});

function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: { rowid: number }) => id === item.rowid)[0]);
}

async function save(id: number) {
  Object.assign(data?.value?.filter((item: { rowid: number }) => id === item.rowid)[0], editableData[id]);
  // const newData = Object.assign(data?.value?.filter((item: { id: number }) => id === item.id)[0], editableData[id]);
  // const updateDate = {
  // }
  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}

function onDelete(id: number) {
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: { rowid: number }) => item.rowid !== id);
    },
  });
}

// 转成excel
// async function exportExcel() {
//   const workbook = new ExcelJS.Workbook();
//   const worksheet = workbook.addWorksheet('sheet1');
//   worksheet.columns = header;
//   for (let index = 0; index < data.value.length; index++) {
//     worksheet.addRow(data.value[index]);
//   }
//   await workbook.xlsx.writeBuffer().then((buffer) => {
//     const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
//     const url = URL.createObjectURL(blob);
//     const a = document.createElement('a');
//     a.href = url;
//     a.download = 'report.xlsx';
//     document.body.appendChild(a);
//     a.click();
//     document.body.removeChild(a);
//     URL.revokeObjectURL(url);
//   }).catch((err) => {
//     console.error(err);
//   });
// }

// 添加行
let rowid = 1;
function addGo() {
  const correctData = header.reduce((acc, headerItem) => {
    acc[headerItem.key] = '';
    acc.rowid = rowid;
    return acc;
  }, {});
  rowid++;
  data.value.push(correctData);
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            新建表:{{ sheetName }}
          </div>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button type="primary" @click="addGo">
            添加行
          </a-button>
          <a-button type="primary" @click="saveExcel">
            保存
          </a-button>
          <a-button type="primary" @click="$router.push('/assessment_indicators/newexcelheader');">
            返回
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-table
        :columns="columns" :data-source="data" row-key="id" :scroll="{ x: 1024 }" class="q-table"
        :pagination="false"
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.rowid]">
                <a-typography-link @click="save(record.rowid)">保存</a-typography-link>
                <a @click="cancel(record.rowid)">取消</a>
              </span>
              <span v-else>
                <a-space>
                  <a @click="edit(record.rowid)">编辑</a>
                  <a v-if="data.length" @click="onDelete(record.rowid)">删除</a>
                </a-space>
              </span>
            </div>
          </template>
          <template v-else>
            <div>
              <a-input
                v-if="editableData[record.rowid]"
                v-model:value="editableData[record.rowid][column.dataIndex as string]" style="margin: -5px 0;"
                :class="`${column.dataIndex}${record.rowid}`"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .q-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
